<template>
  <div class="selectLocation">


    <div class="project_map" id="project_map" ref="container" style="width: 100%; height: 600px ; z-index:99999"></div>
    <div id="result" style="  display: flex;
              flex-direction: row;">
      <p> 当前选择详细的地址:</p>
      {{ choseLocation }}
    </div>
    <div id="result" style="  display: flex;
               flex-direction: row;">
      <p> 当前选择详细的经纬度:</p>
      {{ choseCoordinates }}

    </div>

    <div style="width:800px; position: absolute; z-index: 99; top: -30px; left: 20px">
      地址搜索 <el-input size="small" style="width:650px;" v-model="keyWord">

      </el-input>
      <el-button @click="queryByKyword()" style="margin-left: 10px;" type="primary" size="small">
        定位
      </el-button>
    </div>

    <el-button type="primary" size="small" style="position: absolute; z-index: 99; top: -30px; right: 40px"
      @click="confirmLocation()">
      确定</el-button>


  </div>
</template>
<script setup>
import { onMounted, ref } from 'vue';
import axios from 'axios';
// import "ol/ol.css";
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import Feature from 'ol/Feature';
import VectorSource from 'ol/source/Vector';
import VectorLayer from 'ol/layer/Vector'
import Point from "ol/geom/Point";
import { Icon, Style } from "ol/style";

// import { Map, Object, View } from "ol";
// import {TileLayer} from "ol/layer/Tile";
// import {VectorSource} from "ol/source/Vector";
// import {XYZ} from "ol/source/XYZ";
// import { Tile as Tilelayer, Vector as VectorLayer } from "ol/layer";
// import {Feature} from "ol/Feature";

// let location = require('@/assets/image/gisIco/location.png')
import location from '@/assets/image/gisIco/location.png'
import { ElMessage } from 'element-plus';

import app from '../../../../public/app/aplication'

let choseLocation = ref("")
let choseCoordinates = ref("")

let keyWord = ref("")
//地图容器
let map;
//矢量地图
let baseMapLayer;
//中文标记
let annotateMapLayer;

//加载资源类
let vectorSource;
//加载的资源图层 
let vectorLayer;
let chosePositionSource;
let chosePositionLayer;

const emit = defineEmits(['choseLocation'])
// 提交位置信息
const confirmLocation = () => {
  emit('choseLocation', choseLocation.value, projectArea, choseCoordinates.value)
}


onMounted(async () => {
  //获取访问者IP
  let IP = localStorage.getItem('Ip')

  let reslut = await axios.post('https://restapi.amap.com/v3/ip?key=3c227d8cdc616d141ffbf89a6a42b536&ip=' + IP)
  map = new Map({
    target: "project_map",
    view: new View({
      projection: "EPSG:4326", //使用这个坐标系
      center: [114.280485, 30.280073],
      zoom: 5,
      maxZoom: 23,
      minZoom: 1,
      // //1.设置缩放级别为整数
      // constrainResolution: false,
      // //2.关闭无级缩放地图
      // smoothResolutionConstraint: false,
    }),
  });

  //     // 天地图  标注
  // let url = "https://t{0-5}.tianditu.com/DataServer?x={x}&y={y}&l={z}";
  // url = `${url}&T=vec_c&tk=875d21df8695479411a73970aa2bf7cf`;
  const source = new XYZ({
    url: app.vec_cUrl,
    projection: "EPSG:4326",
  });
  baseMapLayer = new TileLayer({
    source: source,
  });

  // url = "https://t{0-5}.tianditu.com/DataServer?x={x}&y={y}&l={z}";
  // url = `${url}&T=cva_c&tk=875d21df8695479411a73970aa2bf7cf`;
  const sourceCVA = new XYZ({
    url: app.cva_cUrl,
    projection: "EPSG:4326",
  });

  annotateMapLayer = new TileLayer({
    source: sourceCVA,
  });

  map.addLayer(baseMapLayer);
  map.addLayer(annotateMapLayer);


  map.on("click", (evt) => {
    chosePositionSource.clear()
    let rectangs = evt.coordinate;
    const iconFeature = new Feature({
      geometry: new Point([rectangs[0], rectangs[1]]),

    });
    iconFeature.setStyle((resolution) => {
      return [new Style({
        image: new Icon({
          src: location
        }),
      })

      ];

    });
    chosePositionSource.addFeature(iconFeature)
    queryLoctionParms(rectangs[0], rectangs[1])
  });
  let rectangs = reslut.data.rectangle.split(";")[0].split(",")

  map.getView().animate({ // 只设置需要的属性即可
    center: [rectangs[0], rectangs[1]], // 中心点
    zoom: 12, // 缩放级别
    rotation: undefined, // 缩放完成view视图旋转弧度
    duration: 1000 // 缩放持续时间，默认不需要设置
  })
  queryLoctionParms(rectangs[0], rectangs[1])
  //     // 设计 钻孔图层      
  chosePositionSource = new VectorSource();
  chosePositionLayer = new VectorLayer({
    source: chosePositionSource
  })
  map.addLayer(chosePositionLayer)

  const iconFeature = new Feature({
    geometry: new Point([rectangs[0], rectangs[1]]),

  });

  iconFeature.setStyle((resolution) => {

    return [new Style({
      image: new Icon({
        src: location,
      }),
    })

    ];

  });
  chosePositionSource.addFeature(iconFeature)


})
let projectArea;



const queryLoctionParms = (x, y) => {
  axios.get(app.geocoder+"postStr={'lon':" + x + ",'lat':" + y + ",'ver':1}&type=geocode&tk="+app.govTk
  ).then((res) => {
    choseLocation.value = res.data.result.formatted_address
    projectArea = res.data.result.addressComponent.province + "," + res.data.result.addressComponent.city
    choseCoordinates.value = x + "," + y
  })
}

const queryByKyword = () => {
  axios.get(app.geocoder+`ds={"keyWord":"${keyWord.value}"}&tk=`+app.govTk).then((res) => {
   

    console.log(res);
    if (res.data.status!='0') {
      ElMessage.info("未查询到位置")
      return
    }
    
    chosePositionSource.clear()
    const iconFeature = new Feature({
      geometry: new Point([res.data.location.lon, res.data.location.lat]),

    });
    iconFeature.setStyle((resolution) => {
      return [new Style({
        image: new Icon({
          src: location
        }),
      })

      ];

    });
    chosePositionSource.addFeature(iconFeature)
    map.getView().animate({ // 只设置需要的属性即可
      center: [res.data.location.lon, res.data.location.lat], // 中心点
      zoom: 12, // 缩放级别
      rotation: undefined, // 缩放完成view视图旋转弧度
      duration: 1000 // 缩放持续时间，默认不需要设置
    })
    queryLoctionParms(res.data.location.lon, res.data.location.lat)
  })

}


</script>

<style scoped lang="scss">
.selectLocation {
  p {
    color: rgb(141, 141, 141);
    margin-right: 5px;
  }
}
</style>